package com.zjj.concurrent.disruptor.mainProcess;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.zjj.concurrent.disruptor.consumer.OrderEventHandler;
import com.zjj.concurrent.disruptor.event.OrderEvent;
import com.zjj.concurrent.disruptor.event.OrderEventFactory;
import com.zjj.concurrent.disruptor.producer.OrderEventProducer;

import java.util.concurrent.Executors;

/**
 * @author zhanglei.zjj
 * @description Disruptor使用主流程
 * @date 2023/6/4 18:17
 */
public class DisruptorDemo {
    public static void main(String[] args) {
        //创建disruptor
        Disruptor<OrderEvent> disruptor = new Disruptor<>(
                new OrderEventFactory(),
                1024 * 1024,
                Executors.defaultThreadFactory(),
                ProducerType.SINGLE, //单生产者
                new YieldingWaitStrategy()  //等待策略
        );
        //设置消费者用于处理RingBuffer的事件
        disruptor.handleEventsWith(new OrderEventHandler());
        disruptor.handleEventsWithWorkerPool(new  OrderEventHandler());
        disruptor.start();

        //创建ringbuffer容器
        RingBuffer<OrderEvent> ringBuffer = disruptor.getRingBuffer();
        //创建生产者
        OrderEventProducer eventProducer = new OrderEventProducer(ringBuffer);
        //发送消息
        for (int i = 0; i < 100; i++) {
            eventProducer.onData(i, "Zjj" + i);
        }

        disruptor.shutdown();
    }

}
